package com.bnyy.medicalHousekeeper.moudle.message.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.bnyy.gbp.customsView.ScaleImageView;
import com.bnyy.medicalHousekeeper.DialogHelper;
import com.bnyy.medicalHousekeeper.GlideHelper;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.base.BaseActivityImpl;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.bnyy.message.bean.GroupChatActivityDetail;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2023/1/6
 **/
public class GroupChatActivityDetailActivity extends BaseActivityImpl {
    @BindView(R.id.tv_subject)
    TextView tvSubject;
    @BindView(R.id.iv)
    ScaleImageView iv;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_count)
    TextView tvCount;
    @BindView(R.id.tv_check_all)
    TextView tvCheckAll;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.tv_operate)
    TextView tvOperate;

    private int max = 15;

    public static void show(Context context, int activityId) {
        Intent intent = new Intent(context, GroupChatActivityDetailActivity.class);
        intent.putExtra("activityId", activityId);
        context.startActivity(intent);
    }

    public static void show(Context context, int activityId, ActivityResultLauncher<Intent> launcher) {
        Intent intent = new Intent(context, GroupChatActivityDetailActivity.class);
        intent.putExtra("activityId", activityId);
        launcher.launch(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_group_chat_activity_detail;
    }

    @Override
    public String getTitleStr() {
        return "活动详情";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        recyclerView.setLayoutManager(new GridLayoutManager(mContext, 5));

        getGroupChatActivityDetail(getIntent().getIntExtra("activityId", -1));
    }

    private GroupChatActivityDetail groupChatActivityDetail;

    private void getGroupChatActivityDetail(int activityId) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("activity_id", activityId);
        requestManager.request(requestManager.mMessageRetrofitService.getGroupChatActivityDetail(RequestManager.getJsonRequestBody(params)),
                new BaseObserverImpl<GroupChatActivityDetail>(mContext) {
                    @Override
                    public void onSuccess(GroupChatActivityDetail groupChatActivityDetail) {
                        super.onSuccess(groupChatActivityDetail);

                        GroupChatActivityDetailActivity.this.groupChatActivityDetail = groupChatActivityDetail;

                        tvSubject.setText(groupChatActivityDetail.getSubject());
                        GlideHelper.setHeader(mContext, groupChatActivityDetail.getUser_img(), iv);
                        tvName.setText(groupChatActivityDetail.getUsername());
                        tvSubject.setText(groupChatActivityDetail.getSubject());
                        try {
                            Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(groupChatActivityDetail.getDatetime());

                            if (date != null) {
                                String time;
                                if (TimeUtils.isToday(date)) {
                                    time = new SimpleDateFormat("HH:mm").format(date);
                                } else {
                                    Calendar calendar = Calendar.getInstance();
                                    calendar.setTimeInMillis(System.currentTimeMillis());
                                    int x = calendar.get(Calendar.DAY_OF_YEAR);

                                    calendar.setTimeInMillis(date.getTime());
                                    int y = calendar.get(Calendar.DAY_OF_YEAR);

                                    if (x - y == 1) {
                                        time = "昨天 " + new SimpleDateFormat("HH:mm").format(date);
                                    } else {
                                        time = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date);
                                    }
                                }
                                tvTime.setText(time + "发布");
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        tvCount.setText("已有" + groupChatActivityDetail.getNumber() + "人参与");

                        GradientDrawable bg = new GradientDrawable();
                        bg.setCornerRadius(360);
                        if (groupChatActivityDetail.isJoined()) {
                            bg.setColor(Color.parseColor("#FDF4F5"));
                            tvOperate.setText("退出活动");
                            tvOperate.setTextColor(Color.RED);
                        } else {
                            bg.setColor(ContextCompat.getColor(mContext, R.color.green_theme));
                            tvOperate.setText("参与活动");
                            tvOperate.setTextColor(Color.WHITE);
                        }
                        tvOperate.setBackground(bg);
                        tvOperate.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (groupChatActivityDetail.isJoined()) {
                                    DialogHelper.showNormalDialog(mContext, "温馨提示", "确定要退出本次活动吗？", "暂不退出", "确定退出",
                                            new DialogHelper.Callback() {
                                                @Override
                                                public void onRightClick(AlertDialog alertDialog) {
                                                    super.onRightClick(alertDialog);
                                                    joinActivity(activityId, !groupChatActivityDetail.isJoined());
                                                }
                                            });
                                } else {
                                    joinActivity(activityId, !groupChatActivityDetail.isJoined());
                                }
                            }
                        });

                        ArrayList<GroupChatActivityDetail.UserInfo> userInfos = groupChatActivityDetail.getUserInfos();

                        if (userInfos.size() >= max) {
                            tvCheckAll.setVisibility(View.VISIBLE);
                        } else {
                            tvCheckAll.setVisibility(View.INVISIBLE);
                        }
                        tvCheckAll.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                GroupChatActivityJoinedActivity.show(mContext, userInfos);
                            }
                        });
                        recyclerView.setAdapter(new RecyclerView.Adapter() {

                            @Override
                            public int getItemViewType(int position) {
                                return position == max - 1 ? 1 : 0;
                            }

                            @NonNull
                            @Override
                            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

                                LinearLayout linearLayout = new LinearLayout(mContext);
                                linearLayout.setOrientation(LinearLayout.VERTICAL);
                                linearLayout.setGravity(Gravity.CENTER_HORIZONTAL);
                                linearLayout.setPadding(0, SizeUtils.sp2px(12), 0, 0);
                                int width = ScreenUtils.getScreenWidth() / 10;

                                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, width);
                                layoutParams.setMargins(0, 0, 0, SizeUtils.dp2px(5));
                                ImageView iv = new ImageView(mContext);
                                iv.setImageResource(R.mipmap.icon_default_header_man);
                                linearLayout.addView(iv, layoutParams);

                                TextView tv = new TextView(mContext);
                                tv.setGravity(Gravity.CENTER_HORIZONTAL);
                                tv.setTextAppearance(R.style.NormalTextView);
                                tv.setSingleLine(true);
                                tv.setEllipsize(TextUtils.TruncateAt.END);
                                linearLayout.addView(tv);

                                return new ViewHolder(linearLayout);
                            }

                            @Override
                            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                                ViewHolder viewHolder = (ViewHolder) holder;
                                if (holder.getItemViewType() == 0) {
                                    GroupChatActivityDetail.UserInfo userInfo = userInfos.get(position);
                                    viewHolder.iv.setBackground(null);
                                    GlideHelper.setHeader(mContext, userInfo.getUser_img(), viewHolder.iv);
                                    viewHolder.tv.setText(userInfo.getUsername());

                                    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            UserHomePageActivity.show(mContext, userInfo.getUser_id(), userInfo.getRoleId());
                                        }
                                    });
                                } else {
                                    viewHolder.iv.setBackgroundResource(R.drawable.shape_bg_oval_stroke_gray_light_dash);
                                    viewHolder.iv.setImageResource(R.mipmap.icon_options);
                                    viewHolder.tv.setText("");

                                    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            tvCheckAll.performClick();
                                        }
                                    });
                                }
                            }

                            @Override
                            public int getItemCount() {
                                return Math.min(userInfos.size(), max);
                            }

                            class ViewHolder extends RecyclerView.ViewHolder {

                                ImageView iv;
                                TextView tv;

                                ViewHolder(@NonNull View itemView) {
                                    super(itemView);
                                    LinearLayout linearLayout = (LinearLayout) itemView;
                                    iv = (ImageView) linearLayout.getChildAt(0);
                                    tv = (TextView) linearLayout.getChildAt(1);
                                }
                            }
                        });
                    }
                }
        );
    }

    private void joinActivity(int activityId, boolean join) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("activity_id", activityId);
        params.put("is_activity", join);
        requestManager.request(requestManager.mMessageRetrofitService.joinGroupChatActivity(RequestManager.getJsonRequestBody(params)),
                new BaseObserverImpl<Object>(mContext) {
                    @Override
                    public void onSuccess() {
                        super.onSuccess();
                        getGroupChatActivityDetail(activityId);
                    }
                });
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra("groupChatActivityDetail", groupChatActivityDetail);
        setResult(RESULT_OK, intent);

        super.onBackPressed();
    }
}




















































